package org.jeecg.modules.sistersophie.facade.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.sistersophie.entity.CourseInfo;
import org.jeecg.modules.sistersophie.entity.CourseStudentInfo;
import org.jeecg.modules.sistersophie.entity.StudentInfo;
import org.jeecg.modules.sistersophie.facade.CourseStudentFacade;
import org.jeecg.modules.sistersophie.model.dto.CourseStudentDTO;
import org.jeecg.modules.sistersophie.model.request.CourseAddStudentRequest;
import org.jeecg.modules.sistersophie.model.vo.CourseStudentSearchVO;
import org.jeecg.modules.sistersophie.service.ICourseInfoService;
import org.jeecg.modules.sistersophie.service.ICourseStudentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CourseStudentFacadeService implements CourseStudentFacade {

    @Autowired
    private ICourseStudentInfoService courseStudentInfoService;

    @Autowired
    private ICourseInfoService courseInfoService;

    public CourseStudentInfo selectById(Integer id){
        return courseStudentInfoService.getById(id);
    }

    public void updateInfo(CourseStudentInfo info){
        courseStudentInfoService.updateById(info);
    }

    @Override
    @Transactional
    public void addStudent(CourseAddStudentRequest addStudentRequest) {
        //过滤当前课程中是否存在该学生，如果存在忽略，如果不存在添加
        if(addStudentRequest.getCourseId() != null && CollectionUtils.isNotEmpty(addStudentRequest.getStudents())){
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            //获取课程信息
            CourseInfo courseInfo = courseInfoService.getById(addStudentRequest.getCourseId());
            List<CourseStudentInfo> entityList = new ArrayList<>();
            //验证课程学时信息是否满课
            if(courseInfo.getCourseType() == 1){
                if(courseInfo.getCourseSubType() == null){
                    courseInfo.setMaxStudent(1);
                }else{
                    courseInfo.setMaxStudent(courseInfo.getMaxStudent());
                }
            }
            int num = this.selectCourseStudentCount(addStudentRequest.getCourseId());
            if((num + addStudentRequest.getStudents().size()) > courseInfo.getMaxStudent()){
                throw new RuntimeException("course Name : " + courseInfo.getName() + " Cannot add more students than the maximum number of students");
            }
            String today= DateUtil.today();
            Date now = DateUtil.parse(today, "yyyy-MM-dd");
            Date startTime = courseInfo.getStartTime();

            for(StudentInfo sInfo : addStudentRequest.getStudents()){
                QueryWrapper<CourseStudentInfo>    queryWrapper = new QueryWrapper();
                queryWrapper.eq("course_id",addStudentRequest.getCourseId()).eq("student_id",sInfo.getId())
                        .eq("is_delete",0);
                CourseStudentInfo studentInfo = courseStudentInfoService.getOne(queryWrapper);
                if(studentInfo == null){
                    CourseStudentInfo addInfo = new CourseStudentInfo();
                    addInfo.setCourseId(addStudentRequest.getCourseId());
                    addInfo.setStudentId(sInfo.getId());
                    if(startTime.getTime() > now.getTime()){
                        addInfo.setStudentStatus(0);
                    }else{
                        addInfo.setStudentStatus(1);
                    }
                    addInfo.setPayStatus(0);
                    addInfo.setPrice(courseInfo.getPrice());
                    addInfo.setActualPrice(courseInfo.getPrice());
                    addInfo.setIsDelete(0);
                    addInfo.setCreateTime(new Date()); addInfo.setUpdateTime(new Date());
                    addInfo.setCreateName(sysUser.getUsername());
                    addInfo.setUpdateName(sysUser.getUsername());
                    entityList.add(addInfo);
                }
            }
            if(CollectionUtils.isNotEmpty(entityList)){
                courseStudentInfoService.saveBatch(entityList);
            }
        }
    }

    @Override
    public List<CourseStudentDTO> selectInvoiceCourseStudent(CourseStudentSearchVO searchVO) {
        return courseStudentInfoService.selectInvoiceCourseStudent(searchVO);
    }

    public List<CourseStudentInfo> selectByInvoiceId(Integer invoiceId,Integer payStatus) {
        QueryWrapper<CourseStudentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invoice_id",invoiceId).eq("is_delete",0);
        if(payStatus != null){
            queryWrapper.eq("pay_status",payStatus);
        }
        return courseStudentInfoService.list(queryWrapper);
    }

    public int selectCourseStudentCount(Integer courseId){
        QueryWrapper<CourseStudentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId).eq("is_delete",0);
        return courseStudentInfoService.count(queryWrapper);
    }

    public int selectCourseCountByStudent(Integer studentId){
        QueryWrapper<CourseStudentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id",studentId).eq("is_delete",0);
        return courseStudentInfoService.count(queryWrapper);
    }

    public void deleteCourseStudent(String id){
        //课程中的学生 如果已生成invoice 信息，是不可以进行删除操作的
        CourseStudentInfo courseStudentInfo = this.courseStudentInfoService.getById(id);
        if(courseStudentInfo == null){
            throw new RuntimeException("Student information does not exist");
        }
        if(courseStudentInfo.getInvoiceId() != null && courseStudentInfo.getInvoiceId() > 0 ){
            throw new RuntimeException("The student has invoice("+courseStudentInfo.getInvoiceId()+") information, please delete the invoice before proceeding with this operation");
        }
        this.courseStudentInfoService.removeById(id);
    }
}
